import { isIos, isWx, isH5 } from './is'

export const awaitTo = fn => {
  return async function(...args) {
    try {
      return [null, await fn.apply(this, args)]
    } catch (err) {
      return [err]
    }
  }
}

export const debounce = (fn, t) => {
  const delay = t || 500
  let timer
  return function() {
    const args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      timer = null
      fn.apply(this, args)
    }, delay)
  }
}

/**
 * 获取时间戳,单位秒
 */
export const getTime = (str = '') => {
  let date
  if (str) {
    date = new Date(str)
  } else {
    date = new Date()
  }
  return Date.parse(date) / 1000
}

// 获取当前时间，格式YYYY-MM-DD
export const formatDate = (time = 0, format = 'YYYY-mm-dd HH:ii:ss') => {
  let date
  if (time) {
    if (typeof time === 'number') {
      let multiple = time.toString().length === 10 ? 1000 : 1
      date = new Date(time * multiple)
    } else {
      date = new Date(time)
    }
  } else {
    date = new Date()
  }
  var map = {
    m: date.getMonth() + 1, // 月份
    d: date.getDate(), // 日
    H: date.getHours(), // 小时
    i: date.getMinutes(), // 分
    s: date.getSeconds(), // 秒
    q: Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  format = format.replace(/([YmdHisqS])+/g, function(all, t) {
    var v = map[t]
    if (v !== undefined) {
      if (all.length > 1) {
        v = '0' + v
        v = v.substr(v.length - 2)
      }
      return v
    } else if (t === 'Y') {
      return (date.getFullYear() + '').substr(4 - all.length)
    }
    return all
  })
  return format
}

export const getUrlParam = (key = '') => {
  // #ifdef H5
  var query = window.location.search.substring(1)
  if (!query) {
    return ''
  }
  var vars = query.split('&')
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=')
    if (pair[0] === key) {
      return trim(pair[1], '/')
    }
  }
  // #endif
  return ''
}

// 将object对象转成get形式的字符串 {name: 'xiaomi', age: 10} => name=xiaomin&age=10
export const serialize = (data = {}) => {
  return JSON.stringify(data) === '{}' ? '' : JSON.stringify(data).replace(/["{}]/g, '').replace(/:/g, '=')
    .replace(/,/g, '&')
}

// 删除url指定的参数，names[string,array]
export const delUrlParam = (url = '', names = '') => {
  if (!url) url = window.location.href
  const cutIdx = url.indexOf('?')
  var host = ''
  var query = ''
  var hash = ''
  if (~cutIdx) {
    host = url.slice(0, cutIdx)
    var queryAndHash = url.slice(cutIdx + 1).split('#')
    query = queryAndHash[0]
    hash = queryAndHash[2]
  } else {
    host = url
  }
  if (!query) return url
  var arr = query.split('&')
  var params = {}
  if (typeof names === 'string') {
    names = [names]
  }
  for (var i = 0; i < arr.length; i++) {
    var pair = arr[i].split('=')
    if (names.indexOf(pair[0]) === -1) {
      params[pair[0]] = pair[1]
    }
  }
  hash = hash ? `#${hash}` : ''
  let ser = serialize(params)
  // return ser ? (host + '?' + ser + hash) : host;
  return host + '?' + ser + hash
}

// 更改页面html标题
export const setTitle = (title = '') => {
  document.title = title
  if (isWx() && isIos()) {
    var $iframe = document.createElement('iframe')
    $iframe.style.display = 'none'
    $iframe.onload = function() {
      setTimeout(function() {
        $iframe.remove()
      }, 9)
    }
    document.body.appendChild($iframe)
  }
}

/**
 * 移除左侧
 */
export const ltrim = (str = '', char = '') => {
  var pos = str.indexOf(char)
  return ~pos ? str.substr(0, pos) : str
}

/**
 * 移除右侧
 */
export const rtrim = (str = '', char = '') => {
  var pos = str.lastIndexOf(char)
  return ~pos ? str.substr(0, pos) : str
}

/**
 * 移除两侧
 */
export const trim = (str = '', char = '') => {
  return rtrim(ltrim(str, char), char)
}

// 字符串截取 包含对中文处理,str需截取字符串,start开始截取位置,n截取长度
export const sublen = (str, start, n) => { // eslint-disable-line
  if (str.replace(/[\u4e00-\u9fa5]/g, '**').length <= n) {
    return str
  }
  let len = 0
  let tmpStr = ''
  for (let i = start; i < str.length; i++) { // 遍历字符串
    if (/[\u4e00-\u9fa5]/.test(str[i])) { // 中文 长度为两字节
      len += 2
    } else {
      len += 1
    }
    if (len > n) {
      break
    } else {
      tmpStr += str[i]
    }
  }
  return tmpStr
}

// 倒计时时分秒
export const countdown = (overTime, nowTime = 0) => {
  if (isNaN(Number(overTime))) overTime = Date.parse(overTime.replace(/-/g, '/')) / 1000
  if (!nowTime) nowTime = getTime()
  var total = overTime - nowTime
  var day = Math.floor(total / 86400)
  total = total % 86400
  var hour = Math.floor(total / 3600)
  total = total % 3600
  var minute = Math.floor(total / 60)
  total = total % 60
  var second = total
  return { day, hour, minute, second }
}

// 下拉滑动更多状态
export const getLoading = (loading) => {
  return ['more', 'loading', 'nomore'][loading]
}

export const toFixed = (value, length = 2) => {
  let pow = Math.pow(10, length)
  return Math.round(value * pow) / pow
}

export const getClient = () => {
  let value = 0
  // #ifdef MP-WEIXIN
  value = 1
  // #endif
  return value
}

export const randomStr = len => {
  len = len || 6
  var t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  var a = t.length
  var n = ''
  for (let i = 0; i < len; i++) n += t.charAt(Math.floor(Math.random() * a))
  return n
}

export const href = (url = '') => {
  if (!url) return
  if (isH5()) {
    window.location.href = url
  }
}

export const getSceneParam = (scene = '') => {
  scene = decodeURIComponent(scene)
  let arr = scene.split('&')
  let res = {}
  for (let i = 0; i < arr.length; i++) {
    let [key, val] = arr[i].split('=')
    res[key] = val
  }
  return res
}
